package com.weiqiao.mall.service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.mall.domain.AreaCommodityEntity;
import com.weiqiao.mall.domain.CommodityEntity;
import com.weiqiao.mall.domain.CommodityLogEntity;
import com.weiqiao.mall.domain.MarketActiveEntity;
import com.weiqiao.mall.repository.ICommodityLogRepository;
import com.weiqiao.mall.service.ICommodityLogService;
import com.weiqiao.mall.service.IMarketActiveService;
import com.weiqiao.mall.constant.e.CommodityLogRemarkEnum;
import com.weiqiao.mall.service.vo.CommodityVO;
import com.weiqiao.utils.*;
import org.apache.commons.collections4.CollectionUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商品日志service层
 *
 * @author PENGLIWEI
 * @createDate 2019-10-24
 */
@Service("CommodityLogServiceImpl")
public class CommodityLogServiceImpl implements ICommodityLogService {

    @Autowired
    @Qualifier("CommodityLogRepositoryImpl")
    private ICommodityLogRepository commodityLogRepository;

    @Autowired
    @Qualifier("MarketActiveServiceImpl")
    private IMarketActiveService marketActiveService;

    @Override
    public boolean addCommodityLog(int company_id, CommodityEntity entity, int remarkFlag) {
        // 日志对象
        CommodityLogEntity logEntity = new CommodityLogEntity();
        // 公司id
        logEntity.setCompany_id(company_id);
        // 商品id
        logEntity.setCommodity_id(entity.getCommodity_id());
        // 商品名称
        logEntity.setCommodity_name(entity.getName());
        // 成本价格
        logEntity.setCost_price(entity.getCost_price());
        // 会员价格
        logEntity.setVip_price(entity.getVip_price());
        // 专柜价格
        logEntity.setCounter_price(entity.getPrice());
        // 佣金总额
        logEntity.setCommission(entity.getCommission());
        // 分享立省
        logEntity.setShare_save(entity.getShare_save());
        // 活动实体
        MarketActiveEntity maEntity = entity.getMarketActiveEntity();
        // 专区商品信息实体
        AreaCommodityEntity areaCommodityEntity = entity.getAreaCommodityEntity();

        if (areaCommodityEntity != null && !StringUtil.isBlank(areaCommodityEntity.getCommodity_id())) {
            logEntity.setActive_type(3);
            logEntity.setActive_price(areaCommodityEntity.getArea_price());
            // 佣金
            logEntity.setActive_commission(areaCommodityEntity.getArea_commission());
            // 分享
            logEntity.setActive_share_save(areaCommodityEntity.getArea_share_save());
        } else {
            // 当活动是空的时候 根据活动id查询
            if (StringUtil.isBlank(maEntity)) {
                maEntity = marketActiveService.findOneMarketActive(
                        Filters.and(
                                Filters.eq("active_id", entity.getActive_id()),
                                Filters.eq("delete_flag", 0)
                        ),
                        company_id
                );
            }
            // 活动类型
            // 秒杀
            if (!StringUtil.isBlank(maEntity.getActive_id()) && maEntity.getActive_type() == 0) {
                logEntity.setActive_type(1);
                // 秒杀价格
                logEntity.setActive_price(maEntity.getSpike_price());
                // 拼团
            } else if (!StringUtil.isBlank(maEntity.getActive_id()) && maEntity.getActive_type() == 1) {
                logEntity.setActive_type(2);
                // 拼团价格
                logEntity.setActive_price(maEntity.getAssembly_price());
            }
            // 佣金
            logEntity.setActive_commission(maEntity.getSpike_cmna());
            // 分享
            logEntity.setActive_share_save(maEntity.getSpike_rdim());
        }

        // 备注
        logEntity.setRemark(CommodityLogRemarkEnum.CommodityLogRemark.getNameByValue(remarkFlag));
        //操作人id
        logEntity.setUser_id(SecurityUtils.getUserId().intValue());
        //操作人名称
        logEntity.setUser_name(SecurityUtils.getUsername());
        //ip来源
        logEntity.setIp_config(StringUtils.getIP(SpringUtil.getRequest()));
        // 操作时间
        logEntity.setUpdate_date(String.valueOf(System.currentTimeMillis()));
        return commodityLogRepository.addCommodityLog(new Gson().toJson(logEntity));
    }

    @Override
    public List<CommodityLogEntity> getCommodityLogList(Document doc, Pageable pageable) {
        List<String> list = commodityLogRepository.getCommodityLogList(doc, pageable);
        return this.getCommodityLogEntityList(list);
    }

    @Override
    public Map getCommodityLogList(CommodityVO commodityVO) {
        // 查询条件
        Document doc = new Document().append("company_id", commodityVO.getCompany_id());
        if (!StringUtil.isBlank(commodityVO.getCommodity_id())) {
            doc.append("commodity_id", commodityVO.getCommodity_id());
        }
        if (!StringUtil.isBlank(commodityVO.getCommodity_name())) {
            // 商品名称
            doc.append("commodity_name", new Document("$regex", commodityVO.getCommodity_name()));
        }
        if (!StringUtil.isBlank(commodityVO.getUser())) {
            List<Document> list = new ArrayList<>();
            if (StringUtil.isInteger(commodityVO.getUser())) {
                // 操作者id
                Document doc1 = new Document("user_id", Integer.parseInt(commodityVO.getUser()));
                list.add(doc1);
            }
            // 操作者姓名
            Document doc2 = new Document("user_name", new Document("$regex", commodityVO.getUser()));
            list.add(doc2);
            doc.append("$or", list);
        }
        if (!StringUtil.isBlank(commodityVO.getTime()) && commodityVO.getTime().split("~").length > 1) {
            try {

                String start = commodityVO.getTime().split("~")[0];
                String end = commodityVO.getTime().split("~")[1];
                Date startdate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(start);
                Date enddate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(end);
                if (start.equals(end)) {
                    enddate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(DateUtil.getTomdayDate(new Date()));
                }
                doc.append("update_date", new Document("$gte", String.valueOf(startdate.getTime())).append("$lte",
                        String.valueOf(enddate.getTime())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        // 拼接分页对象
        Sort sort = Sort.by(Sort.Direction.DESC, commodityVO.getSort());
        Pageable pageable = PageRequest.of(commodityVO.getPage(), commodityVO.getSize(), sort);
        // 分页查询日志
        List<String> list = commodityLogRepository.getCommodityLogList(doc, pageable);
        List<CommodityLogEntity> logCommodityList = this.getCommodityLogEntityList(list);
        //查询总记录数
        int total = this.getCommodityLogCount(commodityVO.getCompany_id(), doc);
        //封装返回的对象为map
        Map map = PageUtil.toPage(logCommodityList, total);
        return map;
    }

    @Override
    public int getCommodityLogCount(int company_id, Document doc) {
        return commodityLogRepository.getCommodityLogCount(company_id, doc);
    }

    private List<CommodityLogEntity> getCommodityLogEntityList(List<String> strs) {
        List<CommodityLogEntity> logCommodityList = new ArrayList<>();
        Gson gson = new Gson();
        if (CollectionUtils.isNotEmpty(strs)) {
            for (String str : strs) {
                CommodityLogEntity commodityLogEntity = gson.fromJson(str, CommodityLogEntity.class);
                logCommodityList.add(commodityLogEntity);
            }
        }
        return logCommodityList;
    }
}
